//
//  AddFriendsViewController.m
//  SelfDriving
//
//  Created by apple on 16/2/5.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "AddFriendsViewController.h"
#import "MsgCell.h"
#import "BusinessService+User.h"
#import "FriendDetailsMainVC.h"
#import <MessageUI/MFMessageComposeViewController.h>
#import <Contacts/Contacts.h>
#import <ContactsUI/ContactsUI.h>
#import <AddressBook/AddressBook.h>
#import "qryFriendVC.h"
#import "AddressBookFVC.h"
@interface AddFriendsViewController ()<UITableViewDataSource,UITableViewDelegate,BaseTableDetelage>
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UITextField *suosouField;
@property (weak, nonatomic) IBOutlet BaseTable *table;
@property (weak, nonatomic) IBOutlet UITextField *phoneField;
@property (weak, nonatomic) IBOutlet UIView *inpuView;

@end

@implementation AddFriendsViewController{
    UIView *topview;
    LoginResponseModel*user;
    UILabel *notlabel;
    NSMutableArray *sdata;
    NSMutableString *phone;
    NSMutableArray *phonedata;
    NSMutableArray *redata;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    redata = [[NSMutableArray alloc]init];
    _phoneField.layer.cornerRadius = 13;
    _table.bdelegate = self;
    phonedata = [[NSMutableArray alloc]init];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 5)];
    _phoneField.leftView = view;
    _phoneField.leftViewMode = UITextFieldViewModeAlways;
    
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    [btn addTarget:self action:@selector(qryAction:) forControlEvents:UIControlEventTouchUpInside];
    [btn setBackgroundImage:[UIImage imageNamed:@"fwss1"] forState:UIControlStateNormal];
    _suosouField.rightView = btn;
    _suosouField.rightViewMode = UITextFieldViewModeAlways;
    
    int __block tip=0;
    //声明一个通讯簿的引用
    ABAddressBookRef addBook =nil;
    //因为在IOS6.0之后和之前的权限申请方式有所差别，这里做个判断
    if ([[UIDevice currentDevice].systemVersion floatValue]>=6.0) {
        //创建通讯簿的引用
        addBook=ABAddressBookCreateWithOptions(NULL, NULL);
        //创建一个出事信号量为0的信号
        dispatch_semaphore_t sema=dispatch_semaphore_create(0);
        //申请访问权限
        ABAddressBookRequestAccessWithCompletion(addBook, ^(bool greanted, CFErrorRef error)        {
            //greanted为YES是表示用户允许，否则为不允许
            if (!greanted) {
                tip=1;
            }
            //发送一次信号
            dispatch_semaphore_signal(sema);
        });
        //等待信号触发
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    }else{
        //IOS6之前
        addBook =ABAddressBookCreate();
    }
    if (tip) {
        //做一个友好的提示
        UIAlertView * alart = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请您设置允许APP访问您的通讯录-设置>隐私" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alart show];
    }
    //获取所有联系人的数组
    CFArrayRef allLinkPeople = ABAddressBookCopyArrayOfAllPeople(addBook);
    //获取联系人总数
    CFIndex number = ABAddressBookGetPersonCount(addBook);
    //进行遍历
    for (NSInteger i=0; i<number; i++) {
        //获取联系人对象的引用
        ABRecordRef  people = CFArrayGetValueAtIndex(allLinkPeople, i);
        //获取当前联系人名字
        NSString*firstName=(__bridge NSString *)(ABRecordCopyValue(people, kABPersonFirstNameProperty));
        firstName = firstName?firstName:@"";
        //获取当前联系人姓氏
        NSString*lastName=(__bridge NSString *)(ABRecordCopyValue(people, kABPersonLastNameProperty));
        lastName = lastName?lastName:@"";
        
        //获取当前联系人头像图片
        NSData*userImage=(__bridge NSData*)(ABPersonCopyImageData(people));
        
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        //读取电话多值
        ABMultiValueRef phone = ABRecordCopyValue(people, kABPersonPhoneProperty);
        for (int k = 0; k<ABMultiValueGetCount(phone); k++)
        {
            //获取电话Label
            NSString * personPhoneLabel = (NSString*)CFBridgingRelease(ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k)));
            //获取該Label下的电话值
            NSString * personPhone = (NSString*)CFBridgingRelease(ABMultiValueCopyValueAtIndex(phone, k));
            personPhone = [personPhone stringByReplacingOccurrencesOfString:@"-" withString:@""];
            personPhone = [personPhone stringByReplacingOccurrencesOfString:@"*" withString:@""];
            personPhone = [personPhone stringByReplacingOccurrencesOfString:@"+86" withString:@""];
            personPhone = [personPhone stringByReplacingOccurrencesOfString:@";" withString:@""];
            personPhone = [personPhone stringByReplacingOccurrencesOfString:@" " withString:@""];
            [dic setObject:[NSString stringWithFormat:@"%@",[personPhone trim]] forKey:@"phone"];
        }
        [dic setObject:[NSString stringWithFormat:@"%@%@",lastName,firstName] forKey:@"name"];
        [dic setObject:userImage?userImage:@"" forKey:@"img"];
        [phonedata addObject:dic];
    }
    _table.bdelegate = self;
    phone = [[NSMutableString alloc]init];
    for (int i= 0; i<phonedata.count; i++) {
        NSMutableDictionary *dic = [phonedata objectAtIndex:i];
        if ([dic objectForKey:@"phone"] == nil) {
            continue;
        }
        [phone appendFormat:@"%@,",[dic objectForKey:@"phone"]];
    }
    if ([phone isEqualToString:@""]) {
        [self initData:1];  //xhw2018-2-1改bug14937
//        return;
    }else {
      phone = [phone substringToIndex:phone.length-1];
    }
    _suosouField.delegate = self;
   
    //xhw改bug14937
    [self initData:1];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([scrollView isKindOfClass:[UITextView class]]) {
        return;
    }
    [self.view endEditing:YES];
}
-(void)initData:(int)index{
    //xhw2018-1-17:之前没传经纬度
//    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
    [dic setObject:[NSNumber numberWithInt:index] forKey:@"page"];
    
    LoginResponseModel * defaultUser = [AppDelegate shareDelegate].user;
    [dic setObject:phone forKey:@"phone"];
//    [dic setObject:defaultUser.lat forKey:@"lat"];
//    [dic setObject:defaultUser.lng forKey:@"lng"];
    [[BusinessService shareInstance]recommendList:dic success:^(id result) {
        NSMutableArray *ary = result;
        user = [ary firstObject];
        [redata addObjectsFromArray:user.recommend];
        [redata addObjectsFromArray:user.list];
        [_table reloadData];
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
    
    
    
}
#pragma  mark  查询
- (IBAction)qryAction:(UIButton *)sender {
    [self.view endEditing:YES];
//    NSMutableArray *rary = [[NSMutableArray alloc]init];
//    if([_suosouField.text trim].length!=0){
//        for (int i=0; i<_suosouField.text.length; i++) {
//            NSRange range = NSMakeRange(i,1);
//            NSString *subString = [_suosouField.text substringWithRange:range];
//            const char *cString = [subString UTF8String];
//            if (strlen(cString) == 3 )
//            {
//                NSMutableArray *ary = redata;
//                for (int i=0; i<ary.count;i++) {
//                    LoginResponseModel *model = [[LoginResponseModel alloc]init];
//                    [model serializationWithDictionary:[ary objectAtIndex:i]];
//                    if([model.nickname rangeOfString:_suosouField.text].location !=NSNotFound)//_roaldSearchText
//                    {
//                        [rary addObject:model];
//                    }
//                }
//            }else if(strlen(cString)==1)
//            {
//                for (int i =0; i<redata.count; i++) {
//                    LoginResponseModel *g = [[LoginResponseModel alloc]init];
//                    [g serializationWithDictionary:[redata objectAtIndex:i]];
//                    NSString *n = [ValidateHelper firstCharactor:g.nickname];
//                    if ([n isEqualToString:_suosouField.text.uppercaseString]) {
//                        [rary addObject:g];
//                    }
//                }
//            }
//        }
//    }
//
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:[_suosouField.text trim] forKey:@"name"];
    [SVProgressHUD showWithStatus:@"加载中..."];
    [[BusinessService shareInstance]search:dic success:^(id result) {
        [SVProgressHUD dismiss];
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                     bundle:[NSBundle mainBundle]];
        qryFriendVC *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"qryFriendVC"];
        searchResultDetailController.ary = result;
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
    } failure:^(id result) {
        [SVProgressHUD dismiss];
    }];
    
   
    
    

}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self qryAction:nil];
    return YES;
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 1) {
        return user.recommend.count;
    }
    if (section == 2) {
        if(user.list){
            return user.list.count;
        }else{
            return 0;
        }
    }
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 108;
    }
    return 30;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return @"好友推荐";
    }
    if (section == 2) {
        return @"可能认识的人";
    }
    return nil;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        topview = _topView;
        return topview;
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MsgCell *cell =[tableView dequeueReusableCellWithIdentifier:@"MsgCell"];
    cell.btn.layer.borderColor = colorBG.CGColor;
    cell.btn.layer.borderWidth = 0.5;
    cell.btn.layer.cornerRadius = 5;
    cell.img.layer.cornerRadius = 10;
    cell.img.clipsToBounds = YES;
     while ([cell.selectView.subviews lastObject] != nil) {
        [(UIView*)[cell.selectView.subviews lastObject] removeFromSuperview];
    }
    if (indexPath.section == 1) {
        LoginResponseModel *duser  = [[LoginResponseModel alloc]init];
        [duser serializationWithDictionary:[user.recommend objectAtIndex:indexPath.row]];
        cell.btn.model = duser;
        BaseButton *btn =[[BaseButton alloc]initWithFrame:CGRectMake(0, 75/2-cell.selectView.frame.size.height/2,cell.selectView.frame.size.width, cell.selectView.frame.size.height)];
        [btn setImage:[UIImage imageNamed:@"ttg_d"] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"ttg_s"] forState:UIControlStateSelected];
        [btn addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = indexPath.row+1;
        btn.model = duser;
        [cell.selectView addSubview:btn];
        for (int i = 0; i<sdata.count; i++) {
            LoginResponseModel *model = [sdata objectAtIndex:i];
            NSString *n1 = duser.nickname;
            NSString *n2 = model.nickname;
            if ([n1 isEqualToString:n2]) {
                btn.selected = YES;
            }
        }
        [ValidateHelper setImage:duser.headsmall img:cell.img istoux:NO];
        cell.name.text = duser.nickname;
        cell.content.text = [NSString stringWithFormat:@"%@ %@",[ValidateHelper DistanceFormat:duser.distance],duser.sign];
        
    }else if (indexPath.section == 2){
        LoginResponseModel *duser  = [[LoginResponseModel alloc]init];
        [duser serializationWithDictionary:[user.list objectAtIndex:indexPath.row]];
        BaseButton *btn =[[BaseButton alloc]initWithFrame:CGRectMake(0, 75/2-cell.selectView.frame.size.height/2,cell.selectView.frame.size.width, cell.selectView.frame.size.height)];
        cell.btn.model = duser;
        [btn setImage:[UIImage imageNamed:@"ttg_d"] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"ttg_s"] forState:UIControlStateSelected];
        btn.tag = indexPath.row+1;
        [btn addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
        btn.model = duser;
        [cell.selectView addSubview:btn];
        for (int i = 0; i<sdata.count; i++) {
            LoginResponseModel *model = [sdata objectAtIndex:i];
            NSString *n1 = duser.nickname;
            NSString *n2 = model.nickname;
            if ([n1 isEqualToString:n2]) {
                btn.selected = YES;
            }
        }
        if ([duser.isfriend intValue]==1) {//已添加好友
            cell.btn.titleLabel.text = @"已添加";
            [cell.btn setTitle:@"已添加" forState:UIControlStateNormal];
            cell.btn.enabled = NO;
        }
         [ValidateHelper setImage:duser.headsmall img:cell.img istoux:YES];
        cell.name.text = duser.nickname;
        cell.content.text = [NSString stringWithFormat:@"%@ %@",[ValidateHelper DistanceFormat:duser.distance],duser.sign];
    }
    return cell;
}
-(void)selectAction:(BaseButton *)btn{
    btn.selected = !btn.selected;
    if (btn.selected) {
        [sdata addObject:btn.model];
    }else{
        [sdata removeObject:btn.model];
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
        LoginResponseModel *userd = [[LoginResponseModel alloc]init];
        if (indexPath.section == 1) {
            [userd serializationWithDictionary:[user.recommend objectAtIndex:indexPath.row]];
        }else if (indexPath.section == 2){
            [userd serializationWithDictionary:[user.list objectAtIndex:indexPath.row]];
        }
        DTModel *model = [[DTModel alloc]init];
        model.uid = userd.uid;
    
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                     bundle:[NSBundle mainBundle]];
        FriendDetailsMainVC *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"FriendDetailsMainVC"];
        searchResultDetailController.model = model;
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
}
#pragma  mark 添加好友
- (IBAction)addFriendsAction:(BaseButton *)sender {
    LoginResponseModel *model = sender.model;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:@"0" forKey:@"type"];
    [dic setObject:model.uid forKey:@"fid"];
    [[BusinessService shareInstance]follow:dic success:^(id result) {
        [SVProgressHUD showSuccessWithStatus:@"添加成功"];
        [_table Refresh];
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
}

#pragma 添加通讯录
- (IBAction)addrebook:(UIButton *)sender {
    
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    AddressBookFVC *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"AddressBookFVC"];
    searchResultDetailController.phone = phone;
    searchResultDetailController.ary = phonedata;
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
    
}








- (IBAction)backAction:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
